package com.orange.core.config.convert;

import com.orange.core.pojo.enums.ConvertableEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@RequiredArgsConstructor
@Component
public class EnumConverterFactory implements ConverterFactory<String, ConvertableEnum> {

    @NonNull
    @Override
    public <T extends ConvertableEnum> Converter<String, T> getConverter(@NonNull Class<T> targetType) {
        return new IntegerToEnum<>(targetType);
    }

    private static class IntegerToEnum<T extends ConvertableEnum> implements Converter<String, T> {

        private final T[] values;

        private IntegerToEnum(Class<T> targetType) {
            this.values = targetType.getEnumConstants();
        }

        @Override
        public T convert(@NonNull String source) {
            return Arrays.stream(values).filter(t -> t.getValue() == Integer.parseInt(source)).findFirst().orElse(null);
        }
    }
}
